import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'dart:typed_data';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:hc_ui/config/hc_customer_config.dart';
import 'package:hc_ui/theme/hc_avatar_theme.dart';
import 'package:hc_ui/utils/hc_color_util.dart';
import '../../utils/hc_file_util.dart';
import '../../utils/hc_string_util.dart';

///  头像组件
class HcAvatar extends StatelessWidget {
  // 头像大小
  final double? size;

  //头像圆角
  final double? radius;

  //文字颜色
  final Color? textColor;

  //背景色
  final Color? backgroundColor;

  //背景的渐变
  final Gradient? gradient;

  //文字样式
  final TextStyle? textStyle;

  //边框颜色
  final Color? borderColor;

  //边框大小
  final double? borderWidth;

  //变化的时间
  final int? changeDuration;

  //阴影效果
  final List<BoxShadow>? boxShadow;

  //图片背景Url 图片优先级大于渐变大于背景色
  final String? backgroundImageUrl;

  //图片前景Url
  final String? foregroundImageUrl;

  //出错的回调
  final ImageErrorListener? onForegroundImageError;

  //出错的回调
  final ImageErrorListener? onBackgroundImageError;

  //子组件
  final Widget? child;

  final String? name;

  final HcAvatarTheme? themeData;

  const HcAvatar(
      {Key? key,
      this.child,
      this.backgroundImageUrl,
      this.foregroundImageUrl,
      this.onForegroundImageError,
      this.onBackgroundImageError,
      this.size,
      this.radius,
      this.textColor,
      this.backgroundColor,
      this.gradient,
      this.textStyle,
      this.borderColor,
      this.borderWidth,
      this.changeDuration,
      this.boxShadow,
      this.themeData,
      this.name})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    Color? effectiveTextColor = textColor;
    HcAvatarTheme theme = themeData ?? HcAvatarTheme();

    if (textColor == null) {
      effectiveTextColor = HcColorUtil.needLightColor(
              backgroundColor ?? theme.commonTheme.primaryColor)
          ? theme.commonTheme.textInverseColor
          : theme.commonTheme.textBaseColor;
    }
    double avatarSize = size ?? theme.size;
    double fontSize = theme.commonTheme.fontSizeBase;
    double fontHeight = textStyle?.height ?? theme.commonTheme.fontHeightLg;
    double totalHeight = max(32, min(48, avatarSize));
    double scale = (min(avatarSize, totalHeight) - 16) / 4;
    fontSize = fontHeight + scale * (scale > 0 ? 2 : 1);
    TextStyle finalTextStyle = textStyle ??
        TextStyle(height: theme.commonTheme.fontHeightLg, fontSize: fontSize);
    theme =
        HcCustomerConfig().allTheme.avatarTheme.merge(theme.merge(HcAvatarTheme(
              size: size,
              radius: radius,
              backgroundColor: backgroundColor,
              changeDuration: changeDuration,
              borderColor: borderColor,
              borderWidth: borderWidth ?? (borderColor != null ? 1 : 0),
              textColor: effectiveTextColor,
              textStyle: finalTextStyle,
            )));

    BoxDecoration decoration = BoxDecoration(
        color: theme.backgroundColor,
        gradient: gradient,
        boxShadow: boxShadow,
        border: Border.all(
            color: theme.borderColor,
            width: theme.borderWidth,
            style:
                theme.borderWidth > 0 ? BorderStyle.solid : BorderStyle.none),
        borderRadius: BorderRadius.circular(theme.radius));

    return AnimatedContainer(
      width: theme.size,
      height: theme.size,
      duration: Duration(milliseconds: theme.changeDuration),
      decoration: decoration.copyWith(
          image: backgroundImageUrl != null
              ? DecorationImage(
                  image: _buildImageProvider(backgroundImageUrl),
                  onError: onBackgroundImageError ??
                      (Object exception, StackTrace? stackTrace) {
                        debugPrint('onBackgroundImageError:$exception');
                      },
                  fit: BoxFit.cover,
                )
              : null),
      foregroundDecoration: foregroundImageUrl != null
          ? BoxDecoration(
              image: DecorationImage(
                image: _buildImageProvider(foregroundImageUrl!),
                onError: onForegroundImageError ??
                    (Object exception, StackTrace? stackTrace) {
                      debugPrint('onForegroundImageError:$exception');
                    },
                fit: BoxFit.cover,
              ),
              border: Border.all(
                  color: theme.borderColor,
                  width: theme.borderWidth,
                  style: theme.borderWidth > 0
                      ? BorderStyle.solid
                      : BorderStyle.none),
              borderRadius: BorderRadius.circular(
                  (theme.size + theme.borderWidth * 2) /
                      (theme.size / theme.radius)))
          : null,
      child: Center(
        child: IconTheme(
          data: IconThemeData(color: effectiveTextColor),
          child: DefaultTextStyle(
            style: theme.textStyle,
            child: child ?? Text(HcStringUtil.formatterAvatarName(name)),
          ),
        ),
      ),
    );
  }

  ImageProvider _buildImageProvider(imagePath) {
    Map<String, dynamic> imageInfo = HCFileUtil.checkAndFixImagePath(imagePath);
    HcImageType type = imageInfo['type'];
    imagePath = imageInfo['url'];
    ImageProvider imageProvider = AssetImage(imagePath);
    switch (type) {
      case HcImageType.assets:
        imageProvider = AssetImage(imagePath);
        break;
      case HcImageType.file:
        imageProvider = FileImage(File(imagePath));
        break;
      case HcImageType.base64:
        Uint8List bytes = const Base64Decoder().convert(imagePath);
        imageProvider = MemoryImage(bytes);
        break;
      case HcImageType.network:
        imageProvider = CachedNetworkImageProvider(imagePath);
        break;
    }

    return imageProvider;
  }
}
